/** @format */
import { createVNode, render, VNode, App } from 'vue';
import MessageComponent from './Index.vue';

export type MessageType = 'success' | 'warning' | 'error' | 'info';

export interface MessageOptions {
  id?: string;
  message?: string;
  type?: MessageType;
  duration?: number;
  showClose?: boolean;
  onClose?: () => void;
  customClass?: string;
  customStyle?: object;
}

interface MessageInstance {
  id: string;
  vnode: VNode;
  vm: any;
  handler: MessageHandler;
}

type MessageHandler = {
  close: () => void;
};

const instances: MessageInstance[] = [];
let seed = 1;

const MMessage = (options: MessageOptions | string = {}): MessageHandler => {
  if (typeof options === 'string') {
    options = {
      message: options,
    };
  }

  const id = `m_message_${seed++}`;
  const userOnClose = options.onClose;

  const container = document.createElement('div');

  options.onClose = () => {
    close(id, userOnClose);
  };

  const props = {
    ...options,
    id,
  };

  const vnode = createVNode(MessageComponent, props);
  render(vnode, container);

  const vm = vnode.component?.proxy;
  const handler: MessageHandler = {
    close: () => {
      if (vm && typeof (vm as any).close === 'function') {
        (vm as any).close();
      }
    },
  };

  // 确保firstElementChild存在后再添加到body
  const element = container.firstElementChild;
  if (element) {
    document.body.appendChild(element);
  } else {
    console.error(
      'MMessage component rendering failed: No element was created',
    );
    return handler;
  }

  const instance: MessageInstance = {
    id,
    vnode,
    vm,
    handler,
  };

  instances.push(instance);

  return handler;
};

// 关闭消息
const close = (id: string, userOnClose?: () => void) => {
  const idx = instances.findIndex((instance) => instance.id === id);
  if (idx === -1) return;

  const { vm } = instances[idx];
  if (!vm) return;

  userOnClose?.();
  instances.splice(idx, 1);
};

// 关闭所有消息
export const closeAll = (): void => {
  for (let i = instances.length - 1; i >= 0; i--) {
    instances[i].handler.close();
  }
};

// 创建不同类型的消息方法
const createMessage = (type: MessageType) => {
  return (options: MessageOptions | string = {}) => {
    if (typeof options === 'string') {
      options = {
        message: options,
      };
    }
    return MMessage({
      ...options,
      type,
    });
  };
};

// 导出不同类型的消息方法
MMessage.success = createMessage('success');
MMessage.warning = createMessage('warning');
MMessage.error = createMessage('error');
MMessage.info = createMessage('info');
MMessage.closeAll = closeAll;

// 用于Vue插件安装
MMessage.install = (app: App): void => {
  app.config.globalProperties.$mMessage = MMessage;
};

export default MMessage;
